package com.k.kc.util;

import javax.annotation.Nonnull;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author kkk
 */
public class UrlUtils {
    /**
     * buildHttpGetParams
     *
     * @param uriStr    uri
     * @param paramsMap map
     * @param charset   charset
     * @return result
     */
    public static String buildUriQueryParameters(@Nonnull String uriStr, @Nonnull Map<String, String> paramsMap, @Nonnull Charset charset) {
        URI uri = URI.create(uriStr);
        String query = uri.getQuery();
        String connectDelimiter = (query == null || query.trim().length() == 0) ? "?" : "&";
        uriStr = uri + connectDelimiter;
        String kvPair = paramsMap.entrySet().stream()
                .map(itm ->
                {
                    try {
                        return itm.getKey() + "=" + URLEncoder.encode(String.valueOf(itm.getValue()), charset.name());
                    } catch (Exception e) {
                        throw new RuntimeException("URL Encode exception", e);
                    }
                })
                .collect(Collectors.joining("&"));
        return uriStr + kvPair;
    }

    public static String buildUriQueryParameters(String uriStr, Map<String, String> paramsMap) {
        return buildUriQueryParameters(uriStr, paramsMap, StandardCharsets.UTF_8);
    }

    public static Map<String, String> getQueryMap(URI uri) {
        Map<String, String> queryMap = new LinkedHashMap<>();
        String query = uri.getQuery();
        if (query != null) {
            for (String param : query.split("&")) {
                String[] pair = param.split("=", 2);
                if (pair.length > 1) {
                    queryMap.put(pair[0], pair[1]);
                } else {
                    queryMap.put(pair[0], "");
                }
            }
        }
        return queryMap;
    }

    public static Map<String, String> getQueryMap(String uri) {
        return getQueryMap(URI.create(uri));
    }

    // ===================================
    // test
    // ===================================

    public static void main(String[] args) {
        test();
    }

    /**
     * 测试
     * 构建 url get参数
     * 解析 url get参数
     */
    public static void test() {
        String uri = "http://127.0.0.1:8080/index";
        System.out.println("1 uri: " + uri);

        Map<String, String> addGetParamsMap = new HashMap<>();
        addGetParamsMap.put("a", 2 + "");
        addGetParamsMap.put("b", "的的");
        System.out.println("2 addGetParamsMap: " + addGetParamsMap);
        try {
            String uriReq = buildUriQueryParameters(uri, addGetParamsMap);
            System.out.println("3 uriReq:" + uriReq);

            Map<String, String> parseGetParamsMap = getQueryMap(uriReq);
            System.out.println("4 parseGetParamsMap:" + parseGetParamsMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
